<template>
  <div class="auth-container" :style="{ backgroundImage: 'url(/public/covers/12.jpg)' }">
    <div class="welcome-message">
      欢迎进入基于协同过滤的考研信息分享平台
    </div>
    <el-card class="auth-card">
      <h2 class="title">登录</h2>
      <el-form :model="loginForm" label-width="80px" @submit.prevent="handleLogin">
        <el-form-item label="用户名">
          <el-input v-model="loginForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="button-container">
            <el-button type="primary" @click="handleLogin">登录</el-button>
            <el-button type="primary" @click="goToRegister">注册</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import axiosInstance from '../plugins/axios' // 导入 axios 实例

// Vuex Store 和 Router
const store = useStore()
const router = useRouter()

// 登录表单数据
const loginForm = ref({
  username: '',
  password: ''
})

// 登录方法
const handleLogin = async () => {
  try {
    const response = await axiosInstance.post('/users/login', loginForm.value)
    if (response.data.status === 200) {
      console.log('登录成功:', response.data)
      console.log('保存成功:', response.data.user)
      store.dispatch('login', response.data.user) // 保存数据到 Vuex
      if (response.data.user.role == 'ROLE_ADMIN')
        router.push('/admin')
      else
        router.push('/home') // 跳转到首页
    } else {
      console.error('登录失败:', response.data.message)
      alert(response.data.message)
    }
  } catch (error) {
    console.error('网络错误:', error)
    alert('网络错误，请稍后再试')
  }
}

// 跳转到注册页
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.auth-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-size: cover;
  background-position: center;
  position: relative;
}

.welcome-message {
  font-size: 24px;
  color: white;
  text-shadow: 0 0 10px rgba(0, 0, 0, 0.7);
  margin-bottom: 20px;
  text-align: center;
  z-index: 2;
  position: relative;
}

.auth-card {
  width: 400px;
  padding: 20px;
  text-align: center;
  z-index: 2;
  position: relative;
}

.title {
  text-align: center;
}

.button-container {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  padding-left: 25px;
  gap: 20px;
}
</style>